package com.kingeid.hlj.h5;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.kingeid.hlj.h5.bean.UpdateInfo;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import cn.eid.service.kingeid.RespParams;
import cn.eid.service.kingeid.eIDSignEngine;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    public static final int REQUEST_CODE_SCAN = 1001;
    private cn.eid.service.kingeid.eIDSignEngine signEngine;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.tvMessage);
        findViewById(R.id.btnH5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PermissionUtils.isGranted(new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE})) {
                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
                PermissionUtils.permission(new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE}).request();

            }
        });
        Intent intent = new Intent();
        intent.setAction("cn.eid.service.action");
        //从 Android 5.0开始 隐式Intent绑定服务的方式已不能使用,所以这里需要设置Service所在服务端的包名
        intent.setPackage("com.kingeid.wallet");
        bindService(intent, connection, BIND_AUTO_CREATE);
        findViewById(R.id.btnCheckUpdate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (signEngine != null) {
                    try {
                        RespParams respParams = signEngine.geteIDInfo();
                        textView.setText(respParams.getResultCode() + " " + respParams.getResultDetail());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "卡包应用未打开", Toast.LENGTH_SHORT).show();
                }
//                checkUpdate();
//                Intent intent = new Intent();
//                intent.putExtra("type", "1");
//                intent.addCategory("com.kingeid.wallet");
//                intent.setAction("com.kingeid.wallet.eid.action");
//                startActivityForResult(intent, 100);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    private void checkUpdate() {
        String packageName = getPackageName();
//        String packageName = "com.kingeid.tableserver";//测试写死

        AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestUrl("https://www.kingeid.com/check/" + packageName + "/" + packageName)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder, String result) {
                        try {
                            UpdateInfo updateInfo = new Gson().fromJson(result, UpdateInfo.class);
                            if ("1".equals(updateInfo.getStateCode())) {
                                int nowVersion = getVersionCode();
                                if (updateInfo.getVersionCode() > nowVersion) {
                                    UIData data = UIData.create()
                                            .setTitle(getString(R.string.soft_update_title) + "(版本:" + updateInfo.getAppVersion() + ")")
                                            .setContent(getDisplayUpdateInfo(MainActivity.this, updateInfo))
                                            .setDownloadUrl(updateInfo.getUrl());
                                    return data;
                                } else {
                                    Toast.makeText(MainActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                })
                .setShowNotification(false)
                .setDirectDownload(false)
//                .setForceUpdateListener(new ForceUpdateListener() {
                //强制更新
//                    @Override
//                    public void onShouldForceUpdate() {
//                        finish();
//                    }
//                })
                .executeMission(this);
    }

    public String getDisplayUpdateInfo(Context context, UpdateInfo updateInfo) {
        long size = Long.parseLong(updateInfo.getAppSize());
        String targetSize = byte2FitMemorySize(size);
        String version = updateInfo.getAppVersion();
        final String updateContent = updateInfo.getUpdateInfo();
        StringBuilder stringBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(version)) {
            stringBuilder.append(String.format(getResources().getString(R.string.version_tip), version));
            stringBuilder.append("    ");
        }
        if (!TextUtils.isEmpty(targetSize)) {
            stringBuilder.append(String.format(getResources().getString(R.string.apk_size), targetSize));
            stringBuilder.append("\n\n");
        }
        if (!TextUtils.isEmpty(updateContent)) {
            stringBuilder.append(updateContent);
        }
        return stringBuilder.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Log.i(TAG, "onActivityResult: " + content);
                startUseEid(content);
            }
        }
    }

    private void startUseEid(String data) {
        try {
            Intent intent = new Intent();
            intent.putExtra("data", data);
            intent.addCategory("com.kingeid.wallet");
            intent.setAction("com.kingeid.wallet.eid.action");
            startActivityForResult(intent, 100);
        } catch (ActivityNotFoundException e) {
            ToastUtils.showShort("请先安装海盾信联卡包App");
        }

    }

    /**
     * 字节数转合适内存大小
     * <p>保留 1 位小数</p>
     *
     * @param byteNum 字节数
     * @return 合适内存大小
     */
    @SuppressLint("DefaultLocale")
    private String byte2FitMemorySize(final long byteNum) {
        if (byteNum <= 0) {
            return "";
        } else if (byteNum < 1024) {
            return String.format("%.1f", (double) byteNum);
        } else if (byteNum < 1048576) {
            return String.format("%.1fK", (double) byteNum / 1024);
        } else if (byteNum < 1073741824) {
            return String.format("%.1fM", (double) byteNum / 1048576);
        } else {
            return String.format("%.1fG", (double) byteNum / 1073741824);
        }
    }

    private int getVersionCode() {
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG, "onServiceConnected: " + name.toString());
            signEngine = eIDSignEngine.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            signEngine = null;
            Log.e(TAG, "onServiceDisconnected: " + name.toString());

        }
    };
}
